package com.chzc.fm.duotin.ui.home;

import android.graphics.drawable.Drawable;
import android.support.v4.view.ViewPager;
import android.util.Log;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.ScrollView;

import com.chzc.fm.duotin.R;
import com.chzc.fm.duotin.adapter.viewpager.HomeBannerAdapter;
import com.chzc.fm.duotin.bean.home.RecommendColumn;
import com.chzc.fm.duotin.bean.home.RecommendData;
import com.chzc.fm.duotin.bean.home.RecommendDataList;
import com.chzc.fm.duotin.ui.home.utils.HomeUtils;
import com.chzc.fm.duotin.ui.other.BaseFragment;
import com.chzc.fm.duotin.utils.DuotinTask;
import com.chzc.fm.duotin.utils.LogUtil;
import com.chzc.fm.duotin.widget.HomePannel;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.List;
import java.util.Timer;
import java.util.TimerTask;

/**
 * Created by BillSinla on 2016/6/23.
 */
public class HomeFragment extends BaseFragment{

    public static final int FAKE_BANNER_SIZE = 100;
    public static final int DEFAULT_BANNER = 6;
    private LinearLayout llroot;
    private RelativeLayout llrv;
    private List<ImageView> dots = new ArrayList<>();
    private ViewPager viewPager;
    private Graduate graduate;
    private ScrollView scroll;

    /*设置viewpager轮播效果*/
    private int mBannerPosition = 0;
    private  boolean mIsUserTouched = false;
    private Timer mTimer = new Timer();
    private TimerTask mTask = new TimerTask() {
        @Override
        public void run() {
            if(!mIsUserTouched){
            //进行自动轮播
            getActivity().runOnUiThread(new Runnable() {
                @Override
                public void run() {
                    mBannerPosition = (mBannerPosition+1)%FAKE_BANNER_SIZE;
                    if(mBannerPosition==FAKE_BANNER_SIZE-1){
                        //第二个参数表示滑动效果
                        viewPager.setCurrentItem(DEFAULT_BANNER-1,false);
                    }else{
                        viewPager.setCurrentItem(mBannerPosition);
                    }
                    Log.d("TAG", "tname:" + Thread.currentThread().getName());

                }
            });

            }
        }
    };



    @Override
    protected int getLayoutId() {
        return R.layout.fragment_home;
    }

    @Override
    protected void initViews() {
        //初始化顶部的广告栏
         llroot = (LinearLayout) root.findViewById(R.id.llroot);
         llrv = (RelativeLayout) root.findViewById(R.id.llrv);
         viewPager = (ViewPager) root.findViewById(R.id.vp_banner);
        scroll = (ScrollView) root.findViewById(R.id.scroll);
         graduate = (Graduate) root.findViewById(R.id.graduate);
        for (int i = 0; i < 6; i++) {
            switch (i+1){
                case 1:
                ImageView dot1 = (ImageView) root.findViewById(R.id.dot1);
                    dots.add(dot1);
                break;
                case 2:
                    ImageView dot2 = (ImageView) root.findViewById(R.id.dot2);
                    dots.add(dot2);
                    break;
                case 3:
                    ImageView dot3 = (ImageView) root.findViewById(R.id.dot3);
                    dots.add(dot3);
                    break;
                case 4:
                    ImageView dot4 = (ImageView) root.findViewById(R.id.dot4);
                    dots.add(dot4);
                    break;
                case 5:
                    ImageView dot5 = (ImageView) root.findViewById(R.id.dot5);
                    dots.add(dot5);
                    break;
                case 6:
                    ImageView dot6 = (ImageView) root.findViewById(R.id.dot6);
                    dots.add(dot6);
                    break;
            }
        }
    }

    @Override
    protected void initEvent() {
        graduate.setOnItemClickListener(new Graduate.IOnItemClickListener() {
            @Override
            public void onItemClick(int position) {
                //判断所需要滑动的位置
                LogUtil.e("llroot:"+position);
                int x = (int) llroot.getChildAt(position).getX();
                int y = (int) llroot.getChildAt(position).getY();
                LogUtil.e("x,y"+"( "+x+","+y+" )");
                scroll.scrollTo(x,y);
            }
        });
        viewPager.setOnTouchListener(new View.OnTouchListener() {
            @Override
            public boolean onTouch(View v, MotionEvent event) {
                int action = event.getAction();
                if (action == MotionEvent.ACTION_DOWN
                        || action == MotionEvent.ACTION_MOVE) {
                    mIsUserTouched = true;
                } else if (action == MotionEvent.ACTION_UP) {
                    mIsUserTouched = false;
                }
                return false;
            }
        });
    }

    @Override
    protected void initData() {
        HomeUtils.getRecommend(new DuotinTask.IRequestCallback() {
            @Override
            public void success(Object object) {
                //取到数据
                try {
                    LogUtil.e(object.toString());
                    JSONObject root = new JSONObject(object.toString());
                    //判断数据接受是否成功
                    String msg = root.getString("error_msg");
                    if ("SUCCESS".equals(msg)) {
                        JSONArray data = root.getJSONArray("data");
                        //广告页面
                        List<RecommendData> datas = RecommendData.arrayRecommendDataFromData(data.toString());
                        //索引刻度尺中的文字
                        List<String>list = new ArrayList<String>();
                        for (int i = 0; i < datas.size(); i++) {
                            RecommendData recommendData = datas.get(i);
                            RecommendColumn column = recommendData.getColumn();
                            //添加索引文字
                            list.add(column.getNav());
                            int colmuType = recommendData.getColumn().getColumn();
                            switch (colmuType){
                                case RecommendData.ColumnType.COLUMN_BANNER:
                                    //加入广告页
                                    addBanner( recommendData.getData_list());
                                    break;
                                case RecommendData.ColumnType.COLUMN_LANMU:
                                    //加入栏目
                                    addLanMu(recommendData);
                                    LogUtil.e("lanmu"+i);
                                    break;
                                case RecommendData.ColumnType.COLUMN_TOPIC:
                                    //加入专题
                                    addTopic(recommendData);
                                    break;
                            }
                        }
                        //动态添加完成之后再加一个空view增加用户体验
                        View view = new View(getContext());
                        LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT,80);
                        view.setLayoutParams(params);
                        llroot.addView(view);
                        graduate.setTextList(list);
                        LinearLayout.LayoutParams paramView = new LinearLayout.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT,80);
                        graduate.setLayoutParams(paramView);
                        graduate.invalidate();

                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }
            @Override
            public void error(String msg) {

            }
        });
        mTimer.schedule(mTask,3000,3000);
    }
    private void addTopic(RecommendData data) {

        SpecialTopicPannel topicPannel = new SpecialTopicPannel(getContext(),data);
        llroot.addView(topicPannel);
    }

    private void addLanMu(RecommendData data) {

        HomePannel homePannel = new HomePannel(getContext(),data);
        llroot.addView(homePannel);

    }

    public void addBanner(final List<RecommendDataList> data_list){
      /*  ViewPager viewPager = new ViewPager(getContext());*/
        int width = ViewGroup.LayoutParams.MATCH_PARENT;
        int height =450;
        //为控件设置宽高
        RelativeLayout.LayoutParams rootParams = new RelativeLayout.LayoutParams(width,height);
        viewPager.setLayoutParams(rootParams);
        //设置缓存页数
        viewPager.setOffscreenPageLimit(2);
        List<String> imUrlList= new ArrayList<>();
        List<ImageView>imageViewList = new ArrayList<ImageView>();
        for (int i = 0; i < data_list.size(); i++) {
            //添加图片的地址
            ImageView imageView = new ImageView(getContext());
            //设置imageview的宽高
            ViewPager.LayoutParams params = new ViewPager.LayoutParams();
            params.width = width;
            params.height = height;
            imageView.setLayoutParams(params);
            imUrlList.add(data_list.get(i).getImage_url());
            imageView.setScaleType(ImageView.ScaleType.FIT_XY);
            imageViewList.add(imageView);
            LogUtil.e(data_list.get(i).getImage_url());
        }

        HomeBannerAdapter adapter = new HomeBannerAdapter(getContext(),imageViewList,imUrlList);
        adapter.setDataList(data_list);
        viewPager.setAdapter(adapter);
        //绑定广告页事件
        viewPager.addOnPageChangeListener(new ViewPager.OnPageChangeListener() {
            @Override
            public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {

            }

            @Override
            public void onPageSelected(int position) {
                int temppos = viewPager.getCurrentItem();
                if (temppos==0){
                    position=DEFAULT_BANNER;
                    viewPager.setCurrentItem(temppos,false);
                }else{
                    if(temppos==FAKE_BANNER_SIZE-1){

                        temppos=DEFAULT_BANNER-1;
                        viewPager.setCurrentItem(temppos,false);
                    }
                }

                 //设置指示器
                mBannerPosition = position;
                setIndicator(position);
            }
            @Override
            public void onPageScrollStateChanged(int state) {

            }
        });
        //设置图片点击跳转事件


    }

    private void setIndicator(int position) {
        position %= DEFAULT_BANNER;
        Drawable drawable = getResources().getDrawable(R.drawable.ic_podcast_banner_dot_selected);
        dots.get(position).setImageDrawable(drawable);

        Drawable drawableNormal = getResources().getDrawable(R.drawable.ic_podcast_banner_dot_normal);
        for (int i = 0; i < dots.size(); i++) {
           // LogUtil.e("position"+":"+position+"i"+":"+i);
            if (i!=position){

                dots.get(i).setImageDrawable(drawableNormal);
            }

        }
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        mTimer.cancel();
    }
}
